<?php
/*
$base = new Imagick('orig.jpg');
$mask = new Imagick('mask.png');
$over = new Imagick('over.png');

// Setting same size for all images
$base->resizeImage(274, 275, Imagick::FILTER_LANCZOS, 1);

// Copy opacity mask
//$base->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0, Imagick::CHANNEL_ALPHA);

// Add overlay
//$base->compositeImage($over, Imagick::COMPOSITE_DEFAULT, 0, 0);

//$base->compositeImage($over, Imagick::CONVERT, 32, 32)

$base->writeImage('output.png');


$path = 'images/';

// Create new objects from png's
$dude = new Imagick($path . 'dude.png');
$mask = new Imagick($path . 'dudemask.png');

// IMPORTANT! Must activate the opacity channel
// See: http://www.php.net/manual/en/function.imagick-setimagematte.php
$dude->setImageMatte(1); 

// Create composite of two images using DSTIN
// See: http://www.imagemagick.org/Usage/compose/#dstin
$dude->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0);

// Write image to a file.
$dude->writeImage($path . 'newimage.png');

header("Content-Type: image/png");

echo $base;

//echo $dude;

*/
?>

<?php
include 'includes/inc_cartfuncs.php';
include 'includes/inc_imagefuncts.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script type="text/javascript" defer="defer" src="/js/jquery-1.6.4.js"></script>
  <script type="text/JavaScript" defer="defer" src="/js/jquery.cycle.js"></script>
</head>

<body>

  <div id="wrapper">
    <?php

        /**
          START OF FACTOR FINDING
        **/

        $containerx=100;  // x of samples
        $containery=100;  // y of samples
        $number=92;       // no of samples
        $filecount = count(glob("images/test/*.jpg"));
        //echo $filecount;
        $number=$filecount;
        $master=0;
        echo "Sample image count = ".$number."<br />";

        $img = imagecreatefromjpeg ('images/hero.jpg');
        $containerx = imagesx ($img); // 100
        $containery = imagesy ($img); // 100
        imagedestroy ($img);

        $ratio = $containerx/$containery; // 100/100 = 1
        echo "Ratio value = ".$ratio."<br />";
        $closest=999;

        while($master==0) {
          if ($number==0) {
            $master=1;
            break;
          }
          echo "closest = ".$closest;
          if($closest==999)
            $number=($number-$v);
          echo "<br />TESTING NUMBER = ".$number."<br />";
          $factors=getFactors($number);
          echo "Factors for ".$number." = ";
          print_r($factors);
          $c = count($factors);
          $q=0;
          $v=0;
          $half = $c/2;
          //while($closest==999) {
            
            for($i=0;$i<$half;$i++) {
              $start = $factors[$i];
              $count = ($c-1) - $q;
              $end = $factors[$count];
              $tolerance=($ratio/3);
              echo "<br />Checking factors: ".$start." and ".$end;
              if(($start*$end)==$number) {
                $val = $start/$end;
                $close = abs($val-$ratio); 
                //$offset = round(($ratio/2),2);
                //echo "OFFSET = ".$offset;
                //echo "<br />CLOSE = ".$close;
                //echo "<br />VAL = ".$val;
                //$difference = abs($ratio-$ratio);
                //$val_total=$ratio-$tolerance;
                //echo "VT = ".$val_total;
                //if($close<=$offset) {
                  //$master=1;
                  //if(($val_total<$val)&&($val<$val_total)) {
                  //if($difference<$closest) {
                  if($close<$tolerance) {
                    if ($close<$closest) {
                      $master=1;
                      $closest=$close;
                      echo"<br />HIT on factors ".$start." and ".$end."<br />";
                      $result_x = $start;
                      $result_y = $end;
                    }
                  }
                //}
              }
              $q++;
            //}
          }
          $v++;
        }
        echo "<br />X = ".$result_x."<br />";
        echo "Y = ".$result_y."<br />";
        $a=$result_x;
        $b=$result_y;

        // 100 / 120 = 0.83

        //  9 / 1 = 9
        // 2 / 3



        //$aspect_x=floor($containerx/100);
        //$aspect_y=floor($containery/100);

        /*while($master==0) {                                               // loop through until solution is found
          $factors = getFactors($number);                                 // factors of number of images (first try = original number of images)
          echo "factors for ".$number." ";
          print_r($factors);
          echo "<br />";
          $c = count($factors);                                           // count of factors

          if(($c%2)==1) {                                                 // if number of factors is odd
            while ($c%2==1) {                                             // then loop through
              echo "BBCOUNT = ".$c." AND MOD = ".($c%2)."<br />";
              echo "f = ";
              print_r($factors);
              echo "<br />";
              $number--;                                                  // decrease number by 1
              $factors = getFactors($number);                             // get factors of new number
              $c = count($factors);                                       // count new factors
            }
          }

          $q=0;
          $half_factors = count($factors)/2;
          for($i=0;$i<$half_factors;$i++) {                              // for each factor of number
            $f = $factors[$i];                                           // get first factor (+1 in loop)

            $count = ($c-1)-$q;                                          // last factor (-1 in loop)

            $f_end = $factors[$count];                                   // get last factor (-1 in loop)

            if(($f*$f_end)==$number) {                                   // if factors multiply to give $number (always should)
echo "GETHERE";
echo "<br />fval = ".($f_end-$f);
echo "<br />floor = ".(ceil($number/50));

              if(($f_end-$f)<=(ceil($number/50))) {                      // if high factor - low factor = rounded down $number / 50
                echo "WINNERWINNERWINNER";
                $a = $f;
                $b = $f_end;
                $master=1;                                               // break master loop
              }
            }
            $q++;                                                        // $q is the value used to decrement high factor
          }
          if($master==0)                                                 // if solution is not found, decrease $number by one and re-start
            $number--;
          else {                                                         // else solution
            echo "SAMPLE IMAGES X = ".$a."<br />";
            echo "SAMPLE IMAGES Y = ".$b,"<br /><br /><br />";
          }
          if (($c==0)&&($number==0)) {                                   // error to avoid infinite loop
            echo "ERROR: fail";
            break;
          }
        }*/

        /**
          PUT SAMPLE IMAGES INTO ARRAY
        **/

        $directory= "images/test/";
        $dh  = opendir($directory);
        while (false !== ($filename = readdir($dh))) {
            $ext = substr($filename, strrpos($filename, '.') + 1);
            if(in_array($ext, array("jpg","jpeg","png","gif")))
                $filenames[] = $filename;
        }


        //$x = floor($containerx/$a);
        //$y = floor($containery/$b);

        // loop though each file
        //$v=0;
        //$num_samples=0;
        $grandmaster=999999999;

        /*$directory= "images/test/";
        $files1 = scandir($directory);
        //$dir = '/tmp';
        $dh  = opendir($directory);
        while (false !== ($filename = readdir($dh))) {
            $ext = substr($filename, strrpos($filename, '.') + 1);
            if(in_array($ext, array("jpg","jpeg","png","gif")))
                $filenames[] = $filename;
        }*/

        /**
          GET COLOUR VALUE FOR EACH SAMPLE IMAGE
        **/
        // TODO supply your own filenames
        //$filenames = $files1;
        $v=0;
        foreach ($filenames as $filename) {
          $v++;

          include("colors.inc.php");
          $ex=new GetMostCommonColors();
          $ex->image='images/test/'.$filename;
          $colors=$ex->Get_Color();
          $colors_key=array_keys($colors);

          $averagecols[]=$colors_key[0];
          //echo "<span style=\"background:#".$colors_key[0]."\">".$filename."</span><br />";
        }
        echo "<br />";


          /**
            LOOP THROUGH PIXELS AND MATCH AGAINST SAMPLES
          **/


          // *** Include the class
          // *** 1) Initialize / load image
          $resizeObj = new resize('images/hero.jpg');
          // *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
          $resizeObj -> resizeImage($a, $b, 'exact');
          // *** 3) Save image
          $resizeObj -> saveImage('sample.png', 100);

          $im = imagecreatefrompng("sample.png");

          //echo "aye = ".$a." and bee = ".$b."<br />";
          $t=0;
          for($y=0;$y<$b;$y++) {
            for($x=0;$x<$a;$x++) {
              $flat=0;
              $grandmaster=9999999999;
              $rgb2 = imagecolorat($im, $x, $y);
              $red = ($rgb2 >> 16) & 0xFF;
              $green = ($rgb2 >> 8) & 0xFF;
              $blue = $rgb2 & 0xFF;

              //foreach ($averagecols as $averagecol){
              $count=count($averagecols);
              $c=0;
              while($c<$count) {
                $RGB = toRGB($averagecols[$c]);
                $col = (pow((30*($red-$RGB['R'])),2)) + (pow((59*($green-$RGB['G'])),2)) + (pow((11*($blue-$RGB['B'])),2));
//echo "col = ".$col."<br />";
                if ($col<=$grandmaster)  {
                  $grandmaster=$col;
                  $flag=1;
                  $match=$averagecols[$c];
                  $see=$c;
                }
                $c++;
              }
              //echo "<span style=\"background:".rgb2html($red,$green,$blue)."\">A</span>";
              $width = floor($containerx/$a);
              $height = floor($containery/$b);
              if ($flag==1) {
                echo "<img width=".$width." height=".$height." src=images/test/".$filenames[$see]." />";
                $filelist[]="images/test/".$filenames[$see];
              }
                //echo "<span style=\"background:#".$match."\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>";
              //$col = (pow((30*($r-$RGB['R'])),2)) + (pow((59*($g-$RGB['G'])),2)) + (pow((11*($b-$RGB['B'])),2));

              if ($col<$grandmaster)  {
                $grandmaster=$col;
                //echo "<span style=\"background:#".$colors_key[0]."\">THIS PIXEL IS </span>    <span style=\"background:#".rgb2html($rgb2)."\">THIS </span>    ";
                //echo "<strong>Replaced BEST FIT with: ".$filename."</strong><br />";
              }
              $t++;
            }
            echo "<br />";
          }
          //echo "<span style=\"background:#".$colors_key[0]."\">THIS PIXEL IS </span>    <span style=\"background:#".$averagecol."\">THIS </span><br />";


          //$filelist = array("images/red.jpg","images/yellow.jpg");

          /*$all = new Imagick();
          foreach($filelist as $file){
              $im = new Imagick($file);       
              $all->addImage($im);
          }
          $all->resetIterator();
          $combined = $all->appendImages(true);
          $combined->setImageFormat("png");
          $combined->writeImages('images/composite.png', true); */

          $newWidth = $width*$a;
          $newHeight = $height*$b;
          $newImage = imagecreatetruecolor($newWidth, $newHeight);

          $img = imagecreatefromjpeg ('images/red.jpg');
          $img2 = imagecreatefromjpeg ('images/yellow.jpg');
          $s_width=0;
          $s_height=0;
          $xc=0;
          $yc=0;
          foreach($filelist as $file) {
            $img = imagecreatefromjpeg($file);
            //echo "<br />STATS for ".$file." W = ".$s_width." and H = ".$s_height."<br />";
            imagecopyresampled($newImage, $img, $s_width, $s_height, 0, 0, $width, $height, '100', '100');
            if($xc<($a-1)) {
              $s_width=$s_width+$width;
              $xc++;
              //echo "X = ".$xc."<br />";
            }
            else {
              $s_width=0;
              $xc=0;
              $yc++;
              $s_height=$s_height+$height;
              //echo "Y = ".$yc."<br />";
            } 
            /*if($yc<$b) {
              $s_height=$s_height+$height;
              $yc++;
            }
            else {
              $s_height=0;
              $yc=0;
            }*/
          }

          //$newImage->writeImages('images/comp_new.ong', true);
          imagejpeg($newImage, "images/cont_new.jpg");

          //$luminance = ge t_avg_luminance($filename,count($filenames),$x,$y,$gm,$a,$b);
          $grandmaster=$luminance;
          //echo "AVERAGE LUMINANCE = $luminance<br />";

          // assume a medium gray is the threshold, #acacac or RGB(172, 172, 172)
          // this equates to a luminance of 170
          /*if ($luminance < 50)
            echo '1<br />';
          elseif ($luminance < 100)
            echo "2<br />";
          elseif ($luminance < 150)
            echo '3<br />';
          elseif ($luminance < 200)
            echo '4<br />';
          elseif ($luminance < 250)
            echo '5<br />';
          elseif ($luminance < 300)
            echo '6<br />';
          elseif ($luminance < 350)
            echo '7<br />';
            echo "<br />";
        */
          /*echo "<br /><br />";
          if (($filename != '.') && ($filename != '..')) {
            echo imageshow("images/new");}*/
          exit;


    


    

      if(glob($directory . "*.jpg") != false) {
        $filecount = count(glob($directory . "*.jpg"));
        echo $filecount;
      }
      else
        echo 0;


    function imageshow($dir) {
      //echo "TOTAL = ".count($files1);
      $files = scandir($dir);
      $returnval='';
      $q=0;
      foreach($files as $file) {
        $count[$q] = $file;
        $q++;
        //echo "q = ".$q."<br />";
      }
      sort($count, SORT_NUMERIC);
      for($a=0;$a<count($count);$a++) {
        $returnval.='<img width=50 height=50 src=\'images/new/'.$count[$a].'\' />'; 

        $how_many=0;
        list($colors_key, $colors) = get_avg_colour($a, $count);
        for ($i = 0; $i <= $how_many; $i++)
        {
          $returnval.="<span style='background:#".$colors_key[$i].";width=50px;height=50px;' >".$colors_key[$i]."</span>";
        }
      }
      return $returnval;
    }

    function get_avg_colour($a,$count) {
      if (($a!=0)&&($a!=1)) {
        include_once("colors.inc.php");
        $ex=new GetMostCommonColors();
        //echo "COUNT = ".$count;
        //echo "<br />A = ".$a."<br />";
        //echo "TOTAL = ".$count[$a];
        $ex->image='images/new/'.$count[$a];
        $colors=$ex->Get_Color();
        $how_many=0;
        $colors_key=array_keys($colors);

        return array($colors_key,$colors);
      }
      else
        return false;
    }

    function toRGB($Hex){
      if (substr($Hex,0,1) == "#")
      $Hex = substr($Hex,1);

      $R = substr($Hex,0,2);
      $G = substr($Hex,2,2);
      $B = substr($Hex,4,2);

      $R = hexdec($R);
      $G = hexdec($G);
      $B = hexdec($B);

      $RGB['R'] = $R;
      $RGB['G'] = $G;
      $RGB['B'] = $B;

      return $RGB;
    }



    // get average luminance, by sampling $num_samples times in both x,y directions
    function get_avg_luminance($filename, $num_samples=10,$width,$height,$grandmaster,$a_axis,$b_axis) {
      $image = "images/test/".$filename;
      $new = "images/new/".$filename;
      $num_samples=0;
      //echo "IMAGE = ".$image."<br />";
      $num_samples++;

      @copy($image, $new);
      //echo "NEW IMAGE = ".$new."<br />";

      if ($filename != '.') {
        echo "<br/ >Filename = ".$filename."   ";
        include("colors.inc.php");
        $ex=new GetMostCommonColors();
        $ex->image='images/test/'.$filename;
        $colors=$ex->Get_Color();
        $colors_key=array_keys($colors);

        echo "<span style=\"background:#".$colors_key[0]."\">COLOUR!</span>    ";

        // *** Include the class
        // *** 1) Initialize / load image
        $resizeObj = new resize('images/test/hero.jpg');
        // *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
        $resizeObj -> resizeImage($a_axis, $b_axis, 'exact');
        // *** 3) Save image
        $resizeObj -> saveImage('sample.png', 100);

        $im = imagecreatefrompng("sample.png");

        echo "a = ".$a_axis." and b = ".$b_axis."<br />";
        for($x=0;$x<$a_axis;$x++) {
          for($y=0;$y<$b_axis;$y++) {
            $rgb2 = imagecolorat($im, $x, $y);
            echo "currently on pixel: ".$x, $y."<br />";
            $r = ($rgb2 >> 16) & 0xFF;
            $g = ($rgb2 >> 8) & 0xFF;
            $b = $rgb2 & 0xFF;
            $RGB = toRGB($colors_key[0]);
            $col = (pow((30*($r-$RGB['R'])),2)) + (pow((59*($g-$RGB['G'])),2)) + (pow((11*($b-$RGB['B'])),2));

            if ($col<$grandmaster)  {
              $grandmaster=$col;
              echo "<span style=\"background:#".$colors_key[0]."\">THIS PIXEL IS </span>    <span style=\"background:#".rgb2html($rgb2)."\">THIS </span>    ";
              //echo "<strong>Replaced BEST FIT with: ".$filename."</strong><br />";
            }
          }
        }

        /*$rgb = imagecolorat($im, 0, 2);
        echo "Test pixel colour = ".$rgb."   ";
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;

        $RGB = toRGB($colors_key[0]);*/

        //d2 = (30*(r1-r2))**2 + (59*(g1-g2))**2 + (11*(b1-b2))**2;
        //$col = (pow((30*($r-$RGB['R'])),2)) + (pow((59*($g-$RGB['G'])),2)) + (pow((11*($b-$RGB['B'])),2));
        /*if ($col<$grandmaster)  {
          $grandmaster=$col;
          echo "<strong>Replaced BEST FIT with: ".$filename."</strong><br />";
        }*/

        $width=100; //*** Fix Width & Heigh (Autu caculate) ***//
        $height=100;
        
        $img = imagecreatefromjpeg("images/test/".$filename);
        

        /*$x_step = intval($width/$num_samples);
        $y_step = intval($height/$num_samples);

        $total_lum = 0;

        $sample_no = 1;

        for ($x=0; $x<$width; $x+=$x_step) {
            for ($y=0; $y<$height; $y+=$y_step) {

                $rgb = imagecolorat($img, $x, $y);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                // choose a simple luminance formula from here
                // http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
                $lum = ($r+$r+$b+$g+$g+$g)/6;

                $total_lum += $lum;

                // debugging code
                // echo "$sample_no - XY: $x,$y = $r, $g, $b = $lum<br />";
                $sample_no++;
            }
        }
        // work out the average
        $avg_lum  = $total_lum/$sample_no;
        $extra='';
        $r=0;
        while (file_exists("images/new/".round($avg_lum,2).$extra.".jpg")) {
          $r++;
          $extra=$r;
        }
        rename($new, "images/new/".round($avg_lum,2).$extra.".jpg");*/
        //return $avg_lum;
      }
      return $grandmaster;
    }

    function rgb2html($r, $g=-1, $b=-1)
{
    if (is_array($r) && sizeof($r) == 3)
        list($r, $g, $b) = $r;

    $r = intval($r); $g = intval($g);
    $b = intval($b);

    $r = dechex($r<0?0:($r>255?255:$r));
    $g = dechex($g<0?0:($g>255?255:$g));
    $b = dechex($b<0?0:($b>255?255:$b));

    $color = (strlen($r) < 2?'0':'').$r;
    $color .= (strlen($g) < 2?'0':'').$g;
    $color .= (strlen($b) < 2?'0':'').$b;
    return '#'.$color;
}


    ?>

    <img src="output.jpg">
  </div>
</body>
</html>
